<template>
    <div class="wrap" v-viewer.static="{ title: false, className: 'bg-light' }">
        <viewer class="WH100" :images="[showValue]">
            <img class="WH100" style="object-fit: cover" :src="showValue" />
        </viewer>
    </div>
</template>
<script>
export default {
    name: 'ShowBase',
    props: {
        value: '',
    },
    data() {
        return {
            loading: false,
            showValue: '',
        }
    },
    mounted() {
        this.formMateImgSign()
    },
    methods: {
        addBackgroundColorToBase64Image(base64ImageData, backgroundColor) {
            const img = new Image();
            img.src = base64ImageData;
            return new Promise((resolve, reject) => {
                img.onload = () => {
                    const canvas = document.createElement('canvas');
                    canvas.width = img.width;
                    canvas.height = img.height;
                    const ctx = canvas.getContext('2d');
                    ctx.fillStyle = backgroundColor;
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(img, 0, 0);
                    const newBase64Image = canvas.toDataURL();
                    resolve(newBase64Image);
                };
                img.onerror = (error) => {
                    reject(error);
                };
            });
        },
        formMateImgSign() {
            this.getAxios(this.$addWhiteBackground, { url: this.value }).then((res) => {
                if (res.code == 200) {
                    this.addBackgroundColorToBase64Image(`data:image/png;base64,${res.data}`, 'white')
                        .then((newBase64Image) => {
                            // newBase64Image 是添加了背景颜色后的新图片的 Base64 编码
                            this.showValue = newBase64Image
                        })
                        .catch((error) => {
                        });
                }
            }).catch(() => {
            }).finally(() => {
            })
        }
    }
}
</script>
<style lang="less" scoped>
.wrap {
    width: 100%;
    height: 100%;

    .WH100 {
        width: 100%;
        height: 100%;
    }
}
</style>